package com.epam.dynamiccl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Utility functions for dynamic class loader
 * 
 * @author Iurii Miedviediev
 * @version 1.0 Build 27.07.2014
 */
public class Util {
	
	/**
	 * Check whether class file needs to be compiled/recompiled
	 * @param fileName name of the file to check
	 * @return true if file was modifies, false otherwise
	 */
	public static boolean needsUpdate(String fileName) {
		File javaFile = new File(buildPath(fileName, "src/main/java", ".java"));
		File classFile = new File(buildPath(fileName, "target/classes", ".class"));
		
		return classFile.exists() && javaFile.lastModified() > classFile.lastModified();
	}
	
	/**
	 * Build path to the file
	 * @param name name of the file
	 * @param location location in the project folder
	 * @param extension either .java or .class
	 * @return String representation of the path to the file
	 */
	public static String buildPath(String name, String location, String extension) {
		String fileStub = name.replace('.', File.separatorChar);
		
		StringBuilder fileName = new StringBuilder(
				System.getProperty("user.dir")).append(File.separatorChar)
				.append(location).append(File.separatorChar).append(fileStub)
				.append(extension);
		
		return fileName.toString();
	}
	
	/**
	 * Compile java file
	 * @param filename name of the java file
	 * @throws IOException in case of file not found
	 */
	public static void compile(String filename) throws IOException {
		StringBuilder command = new StringBuilder("javac -d ")
				.append("target/classes").append(" ").append("-cp ")
				.append("src/main/java ").append(filename);
		Process p = Runtime.getRuntime().exec(command.toString(), null);
		try {
			p.waitFor();
		} catch (InterruptedException ie) {
			System.out.println(ie);
		}
	}
	
	/**
	 * Load given file in byte array
	 * @param file File to load
	 * @return array of bytes from the given file
	 * @throws IOException in case of file not found or other IO errors
	 */
	public static byte[] loadClassData(File file) throws IOException {
		byte[] result= new byte[(int)file.length()];
	    FileInputStream f= new FileInputStream(file);
	    f.read(result,0,result.length);
	    f.close();
	    return result;
	}
}
